package com.whatisjee.ssf.misc;


import java.io.IOException;
import java.security.MessageDigest;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.whatisjee.ssf.domain.entity.User;

public final class SecurityUtils {
	private static final Log log = LogFactory.getLog(SecurityUtils.class);
	
	private static final String DEFAULT_ALGORITHM = "MD5";
	private static final int NUM_SALT_BYTES = 8;
	private static final String KEY_CUR_USER = "_CUR_USER";
	
	private SecurityUtils() { }
	
	public static String createPasswordHash(String password) {
		return createPasswordHash(password, null);
	}
	
	public static String createPasswordHash(String password, byte[] salt) {
		String passHash = null;
		
		try {
			byte[] passBytes = password.getBytes();
			MessageDigest md = MessageDigest.getInstance(DEFAULT_ALGORITHM);
			
			if(salt != null) {
				md.update(salt);
			}

			byte[] hashBytes = md.digest(passBytes);
			passHash = bytesToBase64(hashBytes);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("Password hash calculation failed ", e);
			}
		}
		
		return passHash;
	}
	
	public static byte[] createSalt() {
		byte[] salt = new byte[NUM_SALT_BYTES];
		(new Random()).nextBytes(salt);
		return salt;
	}

	public static byte[] base64ToBytes(String data) {		
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = null;
		try {
			bytes = decoder.decodeBuffer(data);
		} catch (IOException e) {
			if (log.isErrorEnabled()) {
				log.error("Decode to BASE64 failed ", e);
			}
		}
		return bytes;
	}

	public static String bytesToBase64(byte[] data) {
		BASE64Encoder endecoder = new BASE64Encoder();
		return endecoder.encode(data);
	}
	
	public static boolean setCurrentUser(User user) {
//		Context s = Contexts.getSessionContext();
//		if(s != null) {
//			s.set(KEY_CUR_USER, user);
//			return true;
//		}
		
		return false;
	}
	
	public static User getCurrentUser(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(KEY_CUR_USER);
		if(user == null) {
			user = new User();
			user.setName("ADMIN");
		}
		String terminal = request.getRemoteHost();
		user.setTerminal(terminal);
		return user;
	}
	
	public static boolean isLoggedIn(HttpServletRequest request) {
		return (getCurrentUser(request).getId() != null);
	}
}